package com.example.myapplication.ui;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.myapplication.adapter.NoteAdapter;
import com.example.myapplication.databinding.FragmentNoteListBinding;

public class NoteListFragment extends Fragment {

    private NoteViewModel noteViewModel;
    private NoteAdapter noteAdapter;
    private FragmentNoteListBinding binding;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 使用 ViewBinding
        binding = FragmentNoteListBinding.inflate(inflater, container, false);
        return binding.getRoot(); // 返回根布局
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 初始化 RecyclerView
        binding.recyclerViewNotes.setLayoutManager(new LinearLayoutManager(requireContext()));

        // 创建 Adapter
        noteAdapter = new NoteAdapter();
        binding.recyclerViewNotes.setAdapter(noteAdapter);

        // 创建 ViewModel
       // noteViewModel = new ViewModelProvider(this).get(NoteViewModel.class);
        noteViewModel = new ViewModelProvider(requireActivity()).get(NoteViewModel.class);

        // 观察数据变化并更新 UI
        noteViewModel.getAllNotes().observe(getViewLifecycleOwner(), notes -> {
            noteAdapter.setNotes(notes);
        });
    }
}
